package pers.cfeng.server.dataManage.dataItem;

import pers.cfeng.common.SubArray;
import pers.cfeng.server.dataManage.DataManagerImpl;
import pers.cfeng.server.dataManage.page.Page;
import pers.cfeng.server.utils.ByteBufferParser;
import pers.cfeng.server.utils.Types;

import java.util.Arrays;

/**
 * Data的数据抽象
 */

public interface DataItem {
    SubArray data();

    void before();
    void unBefore();
    void after(long tid);
    void release();

    void lock();
    void unLock();
    void rLock();
    void rUnLock();

    Page page();
    long getUid(); //更新日志的pageNO + offset
    byte[] getOldRaw();
    SubArray getRaw();

    //wrap
    static byte[] wrapDataItemRaw(byte[] raw) {
        byte[] valid = new byte[1];
        byte[] size = ByteBufferParser.short2Byte((short)raw.length);
        return ByteBufferParser.mergeBytes(valid,size,raw);
    }

    //从页面offset开始解析dataItem
    static DataItem parseDataItem(Page page, short offset, DataManagerImpl dm) {
        byte[] raw = page.getData();
        short size = ByteBufferParser.parseShort(Arrays.copyOfRange(raw, DataItemConstant.OFFSET_SIZE, DataItemConstant.OFFSET_DATA));
        short length = (short)(size + DataItemConstant.OFFSET_DATA); //DataItem总长度
        long uid = Types.addressToUid(page.getPageNumber(), offset);
        return new DataItemImpl(new SubArray(raw, offset, offset + length), new byte[length], page, uid, dm);
    }

    static void setDataItemRawInvalid(byte[] raw) {
        raw[DataItemConstant.OFFSET_VALID] = (byte)1; //删除 --- 有效位变为1失效
    }
}
